package web.controller.common;

import common.consts.Consts;
import common.consts.ContentType;
import common.validation.ValidationResult;
import domain.Device;
import domain.UserLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.ServiceResponse;
import service.SyncupService;
import web.Routes;
import web.controller.Base;
import web.req.SyncupRequest;
import web.security.Protection;

/**
 * Created by aceyin on 15/7/18.
 * APP启动（或者resume）的时候，将用户信息同步到后台。
 * 需要同步的数据包括：
 * <p>
 * 1. 设备信息
 * 2. 用户地理位置信息(注：之前有个地理位置信息接口{@link web.controller.common.Geo})，这个接口启用之后，Geo就不需要了
 */
@RestController
@RequestMapping(Routes.Common.SYNCUP)
public class Syncup extends Base {

    @Autowired
    private SyncupService syncupService;

    @Protection
    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse sync(@RequestBody SyncupRequest request) {
        ValidationResult result = request.validate();
        if (result.isFailed()) {
            return ServiceResponse.fail(result.getMessage());
        }

        long userId = getUserIdFromAuthHeader();

        UserLocation userLocation = copy(request.getGeoRequest(), UserLocation.class);
        if (userLocation == null) {
            return ServiceResponse.fail(Consts.i18nKey.SYSTEM_ERROR);
        }
        Device device = copy(request.getDeviceRequest(), Device.class);
        if (device == null) {
            return ServiceResponse.fail(Consts.i18nKey.SYSTEM_ERROR);
        }

        return syncupService.syncup(userId, userLocation, device);
    }
}
